//
//  CPJPictureView.swift
//  Sina
//
//  Created by YYY on 2017/8/16.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class CPJPictureView: UIView {

    //图片高度约束
    @IBOutlet weak var pictureHeight: NSLayoutConstraint!
    
    var viewModel: CPJListViewModel?
    {
        didSet
        {
            //单图：根据配图视图的大小，计算单张图片宽、高
            if viewModel?.picture_urls?.count == 1
            {
                //单张图
                let viewSize = viewModel?.pictureSize ?? CGSize()
                let imageView = subviews[0]
                imageView.frame = CGRect(x: 0, y: CPJPictureViewOutterMargin, width: viewSize.width, height: viewSize.height - CPJPictureViewOutterMargin)
            }
            else
            {
                //多图 恢复第一张图片大小，呈现九宫格布局
                let imageView = subviews[0]
                imageView.frame = CGRect(x: 0, y: CPJPictureViewOutterMargin, width: CPJPictureItemWidth, height: CPJPictureItemWidth)
            }
            //高度计算
            pictureHeight.constant = viewModel?.pictureSize.height ?? 0
            
            urls =  viewModel?.picture_urls

        }
    }
    
    private var urls: [CPJPictureModel]?
    {
        didSet
        {
            for view in subviews
            {
                //隐藏所有子视图
                view.isHidden = true
            }
            var index = 0
            let modelArray = urls ?? []
            
            for pictureModel in modelArray
            {
                let subImageView = subviews[index] as! UIImageView
                if index == 1 && modelArray.count == 4
                {
                    //处理四张图片
                    index += 1
                }
                subImageView.setImage(urlString: pictureModel.thumbnail_pic,placeholderImage: nil)
                subImageView.isHidden = false
                
                let picString = (pictureModel.thumbnail_pic ?? "") as NSString
                let flag = picString.pathExtension.lowercased() == "gif"
                subImageView.subviews[0].isHidden = !flag
                index += 1
            }
        }
    }
    
    override func awakeFromNib() {
        
        clipsToBounds = true
        //设置背景颜色(父视图背景颜色)
        backgroundColor = superview?.backgroundColor
        
        //创建9个UIImageView
        setupUI()
    }
    
    @objc fileprivate func tapGesture(tap: UITapGestureRecognizer)
    {
        guard let view = tap.view,
            let pictureUrls = viewModel?.picture_urls else
        {
            return
        }
       
        ///
        /// @param selectedIndex    选中照片索引
        /// @param urls             浏览照片 URL 字符串数组
        /// @param parentImageViews 父视图的图像视图数组，用户展现和解除转场动画参照
        var selectedIndex = view.tag
        let urls = (pictureUrls as NSArray).value(forKey: "largePic") as! [String]
        
        if urls.count == 4 && selectedIndex > 1
        {
            selectedIndex -= 1
        }
        //实例化数组中
        var imageViewList = [UIImageView]()
        
        for imageView in subviews as! [UIImageView]
        {
            if !imageView.isHidden
            {
                imageViewList.append(imageView)
            }
        }
        
        //发送通知
        let userInfo = [CPJWeiboCellBrowserPhotoSelectedIndexKey: selectedIndex,
                        CPJWeiboCellBrowserPhotoUrlKey: urls,
                        CPJWeiboCellBrowserPhotoParentImageViewsKey: imageViewList
        ] as [String: AnyObject]
    
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: CPJWeiboCellBrowserPhotoNotification), object: nil, userInfo: userInfo)
    }
}

extension CPJPictureView
{
    fileprivate func setupUI()
    {
        //创建9个UIImageView
        let rect = CGRect(x: 0, y: CPJPictureViewOutterMargin, width: CPJPictureItemWidth, height: CPJPictureItemWidth)
        
        let count = 3
        for i in 0..<count * count
        {
            let img = UIImageView()
            
            //设置图片样式
            img.contentMode = .scaleAspectFit
            img.clipsToBounds = true
            
            let row = CGFloat(i / count)
            let col = CGFloat(i % count)
            
            let xOffset = col * (CPJPictureItemWidth + CPJPictureViewInnerMargin)
            let yOffset = row * (CPJPictureItemWidth + CPJPictureViewInnerMargin)
            
            img.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
           
            addSubview(img)
            
            //打开交互
            img.isUserInteractionEnabled = true
            
            //设置图片tag
            img.tag = i
            //添加手势事件
            let tapImageGesture = UITapGestureRecognizer(target: self, action: #selector(tapGesture))
            img.addGestureRecognizer(tapImageGesture)
            
            //添加GIF提示图像
            addGifView(imageView: img)
        }
    }
    
    //添加GIF视图
    func addGifView(imageView: UIImageView)
    {
        let gifImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        imageView.addSubview(gifImageView)
        
        //自动布局
        gifImageView.translatesAutoresizingMaskIntoConstraints = false
        
        imageView.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .right, relatedBy: .equal, toItem: imageView, attribute: .right, multiplier: 1.0, constant: 0))
        imageView.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .bottom, relatedBy: .equal, toItem: imageView, attribute: .bottom, multiplier: 1.0, constant: 0))
        
        
//        //添加布局
//        gifImageView.left(newLeft: imageView.width - gifImageView.width-10)
//        gifImageView.top(newTop: imageView.height - gifImageView.height-3)
        
        
    }
}
